{% extends 'arya/layout.html' %}
{% load static %}

{% block css %}
    <style>
        .shade {
            position: fixed;
            z-index: 1040;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #999;
            filter: alpha(opacity=50);
            -moz-opacity: 0.5;
            opacity: 0.5;
        }

        .loading {
            position: fixed;
            z-index: 1050;
            top: 40%;
            left: 50%;
            height: 32px;
            width: 32px;
            margin: 0 0 0 -16px;
            background: url(/static/images/loading.gif);
        }

        .save-success {
            color: green;
        }

        .save-error {
            color: red;
        }

        .survery-list {
            border-top: 1px solid #dddddd;

        }

        .survery-list .survery-item {
            padding: 10px 30px;
            border-bottom: 1px dotted #d4d4d4;
            position: relative;
        }

        .survery-list .survery-item .rm-item {
            position: absolute;
            top: 0;
            right: 10px;
            font-size: 20px;
            color: #cccbcb;
            cursor: pointer;
        }

        .survery-list .survery-item textarea {
            height: 60px;
        }

        .survery-list .survery-item .survery-choices {
            padding-left: 15px;
        }

        .survery-list .survery-item .survery-choices li {
            padding: 3px 0;
        }

        .survery-list .survery-item .survery-choices label {
            font-weight: normal;
            padding: 0 5px;
        }

        .survery-list .survery-item .survery-choices input {
            margin-right: 15px;
        }

        .survery-list .survery-item .survery-choices .rm-choice {
            color: #cccbcb;
            cursor: pointer;
        }

        .survery-list ol {
            padding: 0;
            list-style: none;
            counter-reset: sectioncounter
        }

        .survery-list ol > li:before {
            content: '问题' counter(sectioncounter) ':';
            counter-increment: sectioncounter;
            font-size: 18px;
            color: #d4d4d4;
        }

        .survery-list ol > li:nth-of-type(odd) {
            background-color: #f9f9f9;
        }
    </style>

{% endblock %}


{% block breadcrumb %}
    <ol class="breadcrumb">
        <li><a href="#">首页</a></li>
        <li><a href="#">问卷调查</a></li>
        <li class="active">编辑问卷题目</li>

    </ol>
{% endblock %}


{% block content %}
    <div class="clearfix">
        <div style="padding: 0 20px;height: 50px;text-align: right;">
            <span id="saveStatus"></span>
            <input type="button" class="btn btn-success" value="添加" id="btnAddItem"/>
            <input type="button" class="btn btn-primary" value="保存" id="btnSave"/>
        </div>

        <div class="survery-list form-horizontal">
            <ol>
                {% for row in survery_item_list %}
                    <li>
                        <div class="survery-item" pk="{{ row.item.pk }}">
                            <div class="clearfix">
                                <div class="form-group col-sm-12">
                                    <label class="col-sm-1 control-label">问题:</label>
                                    <div class="col-sm-8">{{ row.form.name }}</div>
                                </div>
                                <div class="form-group col-sm-12">
                                    <label class="col-sm-1 control-label">类型:</label>
                                    <div class="col-sm-3">{{ row.form.answer_type }}</div>
                                    <div class="col-sm-2 control-label {{ row.option_class }}" style="text-align: left">
                                        <a class="add-option" href="#"><span class="glyphicon glyphicon-plus"
                                                                             aria-hidden="true"></span>添加选项</a>
                                    </div>
                                </div>
                                <div class="form-group col-sm-12">
                                    <div class="col-sm-offset-1 col-sm-11">
                                        <ul class="survery-choices">
                                            {% for v in row.choices %}
                                                <li pk="{{ v.obj.pk }}">{{ v.form }} <a
                                                        class="glyphicon glyphicon-remove rm-choice"></a></li>
                                            {% endfor %}
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <span class="glyphicon glyphicon-remove rm-item"></span>
                        </div>
                    </li>
                {% endfor %}
            </ol>
        </div>

    </div>


    <!-- 遮罩层开始 -->
    <div id='shade' class='shade hide'></div>
    <!-- 遮罩层结束 -->
    <!-- 加载层开始 -->
    <div id='loading' class='loading hide'></div>
    <!-- 加载层结束 -->
{% endblock %}

{% block js %}
    <script>

        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        });


        $(function () {
            bindSurveryEvent();
        });

        /*
         绑定当前页面所有事件
         */
        function bindSurveryEvent() {
            // 问卷类型变化时，触发是否显示添加选项按钮
            var $surveryList = $('.survery-list');
            $surveryList.on('change', '.answer-type', function () {
                var val = $(this).val();
                if (val == "2") {
                    $(this).parent().next().removeClass('hide');
                } else {
                    $(this).parent().next().addClass('hide');
                    $(this).parent().parent().next().find('.survery-choices').empty();
                }
            });

            $surveryList.on('click', '.add-option', function () {
                var li = '<li><label>内容:</label><input name="content" type="text" required=""> <label>分值:</label><input name="points" type="number"required=""> <a class="glyphicon glyphicon-remove rm-choice"></a></li>';
                $(this).parent().parent().next().find('.survery-choices').append(li);
            });

            $surveryList.on('click', '.rm-choice', function () {
                $(this).parent().remove();
            });

            $surveryList.on('click', '.rm-item', function () {
                $(this).parent().parent().remove();
            });

            $('#btnAddItem').click(function () {
                var itemLi = $surveryList.children().children().first().clone();
                itemLi.find('.survery-item').removeAttr('pk');
                itemLi.find(':text,textarea').val('');
                $surveryList.children().append(itemLi);

            });

            $('#btnSave').click(function () {
                saveSurvery();
            })
        }

        /*
         点击保存按钮，获取所有内容并保存
         */
        function saveSurvery() {


            var postList = [];
            $('.survery-list').find('.survery-item').each(function () {
                var itemId = $(this).attr('pk');
                var itemVal = $(this).find('textarea[name="name"]').val();
                var answerTypeId = $(this).find('select[name="answer_type"]').val();
                var optionList = [];
                if (answerTypeId === "2") {
                    $(this).find('li').each(function () {
                        var optionId = $(this).attr('pk');
                        var content = $(this).find('input[name="content"]').val();
                        var points = $(this).find('input[name="points"]').val();
                        optionList.push({'pk': optionId, 'content': content, 'points': points})
                    })
                }
                postList.push({'pk': itemId, 'name': itemVal, 'answer_type': answerTypeId, 'options': optionList});
            });

            $('#shade,#loading').removeClass('hide');
            $.ajax({
                url: location.href,
                type: 'POST',
                data: JSON.stringify(postList),
                headers: {'Content-Type': "application/json;charset=utf-8"},
                dataType: 'JSON',
                success: function (arg) {
                    if (arg.status === 999) {
                        $('#saveStatus').addClass('save-success').removeClass('save-error').html(arg.data);
                    } else if (arg.status === 1000) {
                        $('#saveStatus').addClass('save-error').removeClass('save-success').html(arg.msg);
                    } else if (arg.status === 1001) {
                        $('#saveStatus').addClass('save-error').removeClass('save-success').html(arg.msg);
                    } else if (arg.status === 1002) {
                        $('#saveStatus').addClass('save-error').removeClass('save-success').html(arg.msg);
                    } else if (arg.status === 1003) {
                        $('#saveStatus').addClass('save-error').removeClass('save-success').html(arg.data);
                    }
                    $('#shade,#loading').addClass('hide');
                },
                error: function () {
                    $('#shade,#loading').addClass('hide');
                }


            })

        }


    </script>


{% endblock %}

